package com.scu.phototabuser.ui.login.login;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import com.scu.phototabuser.Consts;
import com.scu.phototabuser.R;
import com.scu.phototabuser.util.MD5;
import com.scu.phototabuser.util.NetworkUtil;
import com.scu.phototabuser.util.ToastUtil;
import com.scu.phototabuser.widgets.EditTextWithImgLeft;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.scu.phototabuser.util.Predictions.checkNotNull;

/**
 * Created by tianfei on 2017/4/10.
 */

public class SingUpFragment extends Fragment implements LoginContract.SingUpView {

    private LoginContract.Presenter mPresenter;

    private LoginContract.showEmailCallback emailCallback;


    @BindView(R.id.input_email) EditTextWithImgLeft _input_email;

    @BindView(R.id.input_password) EditTextWithImgLeft _input_password;

    @BindView(R.id.input_password_again) EditTextWithImgLeft _input_password_again;


    @OnClick(R.id.link_back_2_login)
    public void back_button_to_login(){
        getFragmentManager().popBackStack();
    }

    @OnClick(R.id.btn_singUp)
    public void doSignUp(){

        if (!NetworkUtil.isNetworkAviliable(getActivity())){
            ToastUtil.makeToast(getActivity(), Consts.NO_NETWORK);
            return;
        }

        //获取输入的内容并校验
        String email = _input_email.getText();
        //String name=_input_name.getText().toString();
        String password = _input_password.getText();
        String password2 = _input_password_again.getText();

        //输入不合法
        if (!validate(email,password,password2)){
            return;
        }

        //提示用户邮箱信息//
        final AlertDialog.Builder alertBuilder=new AlertDialog.Builder(getActivity());
        alertBuilder.setTitle(getString(R.string.hint));
        alertBuilder.setCancelable(true);
        alertBuilder.setMessage(getString(R.string.alert_email_reality));
        alertBuilder.setPositiveButton(getString(R.string.i_am_sure),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        SingUp();
                    }
                });
        alertBuilder.setNegativeButton(getString(R.string.i_will_rethink),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
        alertBuilder.show();

        /////////////////


    }

    private void SingUp(){
        //获取输入的内容并校验
        final String email = _input_email.getText();
        final String password = _input_password.getText();


        final ProgressDialog progressDialog = new ProgressDialog(getActivity(),
                R.style.TransparentProgressDialog);
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(false);
        progressDialog.setMessage("Registering...");
        progressDialog.show();

        String MD5pass= MD5.getMD5(password.getBytes());

        mPresenter.doSignUp(email, MD5pass, new LoginContract.LoginCallback() {
            @Override
            public void showSuccess() {
                progressDialog.cancel();

                emailCallback.showEmail(email);
                //backToLogin
                backToLoginView();
            }

            @Override
            public void showFailed(Integer code,String msg) {
                progressDialog.cancel();
                Log.e("SingUp: onFailed:",code+":"+msg);
                ToastUtil.makeAppContextToast(msg);
            }
        });
    }

    public SingUpFragment(){}

    public static SingUpFragment newInstance(LoginContract.showEmailCallback callback){

        SingUpFragment f=new SingUpFragment();
        f.setEmailCallback(callback);
        return f;
    }

    public void setEmailCallback(LoginContract.showEmailCallback emailCallback) {
        this.emailCallback = emailCallback;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root=inflater.inflate(R.layout.fragment_singup,container,false);
        ButterKnife.bind(this,root);
        return root;
    }

    public boolean validate(String email,String password,String password2) {
        boolean valid = true;

        if (email.contains("%") || email.contains("#") || email.contains("&")
                || email.contains("$")){
            _input_email.setError(Consts.CONTAINS_BAD_CHAR);
            valid=false;
        }else {
            _input_email.setError(null);
        }

        if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            _input_email.setError(Consts.EMAIL_ADDR_ERR);
            valid = false;
        } else {
            _input_email.setError(null);
        }

        if (password.isEmpty() || password.length() < 4 || password.length() > 14) {
            _input_password.setError(Consts.PASSWORD_FORMAT_ERR);
            valid = false;
        } else {
            _input_password.setError(null);
        }

        if (!password2.equals(password)){
            _input_password_again.setError(Consts.PASSWORDS_NOT_EQUALS);
            valid = false;
        }else {
            _input_password_again.setError(null);
        }

        return valid;
    }

    @Override
    public void backToLoginView() {
        getFragmentManager().popBackStack();
    }

    @Override
    public void setPresenter(LoginContract.Presenter presenter) {
        this.mPresenter=checkNotNull(presenter);
    }
}
